package org.jground.rx.ui.zk.viewControl;

import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.rx.IRXObject;
import org.jground.rx.IRXObjectUtils;
import org.jground.rx.RXAttribute;
import org.jground.rx.RXDataState;
import org.jground.rx.RXSearchCriteria;
import org.jground.rx.RXSystem;
import org.jground.rx.RXTypeBackRef;
import org.jground.rx.RXView;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.rx.ui.zk.UIResultList;

public class UIAttributeViewBackref extends UIAttributeViewBase {

    private static Log logger = LogFactory.getLog(UIAttributeViewBackref.class);

    public UIAttributeViewBackref createNew(UIFrame uiFrame, RXView moControl) {
        return new UIAttributeViewBackref(uiFrame, moControl);
    }

    //
    public UIAttributeViewBackref() {}

    private String moidRef;
    private String attRef;
    private RXAttribute moAttribute;
    // private bool isMultiple;
    private RXSearchCriteria searchCriteria;
    private RXAttribute searchAttribute;

    private UIResultList referredData;

    private UIAttributeViewBackref(UIFrame uiFrame, RXView moView) {
        super(uiFrame, moView);
        this.moAttribute = moView.getRXAttribute();
        RXTypeBackRef moType = (RXTypeBackRef) moAttribute.getRXType().getBaseType();
        moidRef = moType.getMoidRef();
        attRef = moType.getAttRef();

        searchCriteria = new RXSearchCriteria();
        searchCriteria.addIncludedDataStates(RXDataState.APPROVED, RXDataState.STORED, RXDataState.NEW);
        searchCriteria.addIncludedMoids(moidRef);
        searchAttribute = RXSystem.getInstance().getRxService().getRXAttribute(moidRef, attRef);
        if (searchAttribute == null) {
            logger.warn("attribute does not exist! : " + moidRef + ", " + attRef);
        }
        referredData = new UIResultList(uiFrame);
        super.add(UIResultList.uiBox(referredData));
    }

    public void set(String... values) {
        clear();
        IRXObject dataContextMod = super.getDataContext();
        if (dataContextMod == null) {
            logger.warn("Data context not set - can not search for back-ref objects");
            return;
        }
        
        Collection<Long> list =  dataContextMod.getBackRefValues(super.rxView.getRXAttribute().getName());    
            List<IRXObject> mods = IRXObjectUtils.oidsToRXDataObject(list);
            referredData.addObjects(mods);
            for (IRXObject mod : mods) {
                super.renderToStringS.add(uiFrame.getUISynopsisRendererFactory().toString(mod));
            }
    }

    public void clear() {
        referredData.removeAllObject();
        renderToStringS.clear();
    }

}